/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.core.utils;

import io.netty.channel.ChannelHandlerContext;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;


/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public final class IpUtil {
    
    public static String getRemoteIp(ChannelHandlerContext ctx){
        InetSocketAddress addr = (InetSocketAddress)ctx.channel().remoteAddress();
        return addr.getAddress().getHostAddress();
    }

    public static Map<String,String> getIPInfos(String ip){
		if(ip==null || ip.equals("")){//illegal IP
			return null;
		}
		String urlStr = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
		 URL url;
			try {
				url = new URL(urlStr);
		        HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
		        urlConn.connect();
		        InputStream is = urlConn.getInputStream();
		        BufferedReader buffer = new BufferedReader(new InputStreamReader(is));
		        StringBuffer bs = new StringBuffer();
		        String l = null;
		        while((l=buffer.readLine())!=null){
		            bs.append(l);
		        }
		        String result  = bs.toString();
		        result.replace("\"", "\'");
		        
		        JSONObject node = JSONObject.parseObject(result);
		        int code = (Integer)node.get("code");
		        if(code==1){//query failed
		        	return null;
		        }
		        Map infoMap = new HashMap();	    
		        JSONObject childNode = (JSONObject)node.get("data");
		        infoMap.put("country",(String)URLDecoder.decode(childNode.getString("country")));
//		        infoList.put("area",(String)URLDecoder.decode(childNode.getString("area")));
		        infoMap.put("region",(String)URLDecoder.decode(childNode.getString("region")));
		        infoMap.put("city",(String)URLDecoder.decode(childNode.getString("city")));
		        return infoMap;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
    }
}
